import {useCallback, useState} from "react";
import { useMutation } from "react-relay";
import {RecordSourceSelectorProxy,} from "relay-runtime";
import {useToast} from "customize-easy-ui-component";
import {Opinion_Enum} from "./__generated__/useFlowReportMutation.graphql";
const graphql = require("babel-plugin-relay/macro");

const mutation = graphql`
  mutation useFlowReportMutation(
    $repId: ID! , $uri:String!, $allow: Opinion_Enum=YES,
    $memo: String , $days: Int
  ) {
     flowReport(repId: $repId, uri: $uri, allow: $allow, memo: $memo, days:$days)
  }
`;

/*流转接口
  flowReport(report: ID!, back: Boolean = false, memo: String, users: [ID]!): String
* */
export default function useFlowReportMutation() {
  const [called, setCalled] =useState<boolean>(false);
  const [result, setResult] =useState<string>('');
  const [commit, doing] = useMutation(mutation);
  const toast = useToast();
  return {
    call:useCallback(
      (repId: string, uri: string, memo: string | null, days: number, allow?: Opinion_Enum) => {
        let disposable= commit({
          variables: {
            repId, memo, uri, allow, days
          },
          onCompleted: (response) => {
            //注意doing在运行到这个位置时刻，就已经是false了，代表后端已经应答doing=false。异步执行，所以结论result不一定马上有的。
            console.log("useCancellationTaskMutation回onCompleted 完成1=", response);
            const { flowReport } = response as { flowReport: boolean };
            setResult( '完成:'+flowReport );
            toast({
              title: "后端回答了",
              subtitle: '应答flowReport='+flowReport,
              intent: "success"
            });
          },
          onError: error => {
            console.log("useCancellationTaskMutation回onError1 =",error);
            setResult( '报错');
            toast({
              title: "后端回答了",
              subtitle: '新Task的ID＝'+error,
              intent: "warning"
            });
          }
        });
        //必须放在commit函数之后的，才会doing逻辑=true生效,doing+called逻辑,保障同步化
        setCalled(true);
        return disposable;
      },
      [commit, toast]
    ),
    doing,
    result,
    called,
    reset: ()=>setCalled(false),
  };
}
